package com.gongpingjialoan.activity.sell;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.category.CategoryActivity;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.adapter.LooperAdapter;
import com.gongpingjialoan.adapter.MaterialAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.BannerBean;
import com.gongpingjialoan.bean.DataManager;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.SellCarPlatBean;
import com.gongpingjialoan.bean.car.SelectShopSucceedData;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.DatePickerDialog;
import com.gongpingjialoan.view.DatePickerDialog.OnDialogCallBack;
import com.gongpingjialoan.view.RLScrollView;
import com.gongpingjialoan.view.SellSameCarDialog;
import com.gongpingjialoan.widget.LoadingDialog;
import com.gongpingjialoan.widget.autoviewpagers.ColorPointHintView;
import com.gongpingjialoan.widget.autoviewpagers.RollPagerView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.gongpingjialoan.api.Piont.SellCarReckonHistory;

/*
 *@author zhanglong
 *Email:1269521147@qq.com
 */
public class WantSellCarActivity extends BaseActivity implements OnClickListener {


    private static final int REQUEST_CAR_TYPE = 1;

    private static final int REQUEST_CITY = 3;

    private NetDataJson mNetModelDetail;

    private LinearLayout channelMainView, channelView1, channelView2, paimaiLinearLayout, jishouLinearLayout;
    //获取商家信息
    private NetDataJson netWork;

    private UserManager mUserManager;
    //选定商家提交
    private NetDataJson subnetWork;

    private TextView carTypeText, dateLicenseText, cityText, history;

    private Button mNextStepBtn, sellcarButton;

    private EditText mDistanceEdit;

    private DatePickerDialog dateDialog;

    private String mYear, mMonth, maxyear, minyear, mBrandSlug, mBrandName, mModelSlug, mModelName, mModelDetailName,
            mModelDetailSlug;

    private LayoutInflater mLayoutInflater;

    private AssessmentData mAssessData;

    private static final int Ass = 1001;

    private LoadingDialog progressDialog;

    private static final int HISTROY = 8;

    private static final int EVAL_HISTORY = 5;

    private String mile;

    private GridView mGridView;

    private RLScrollView mScrollView;

    private SellCarPlatBean sellCarPlatBean;

    private NetDataJson sameNetDataJson;

    private TextView mTextView, mileTypeTextView;

    private ImageView mImageView;

    private List<SellCarPlatBean.CooperationDealersEntity> paimais = new ArrayList<>();
    private List<SellCarPlatBean.CooperationDealersEntity> jishous = new ArrayList<>();
    private List<SellCarPlatBean.CooperationDealersEntity> allPlats = new ArrayList<>();

    private RollPagerView mRollPagerView;

    private boolean isShowBanner = false;

    private LooperAdapter mLooperAdapter;

    private LinearLayout rollLinearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "sell";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_want_sell_car);
        PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarView);
        EventBus.getDefault().register(this);
        setTitle("快速卖车");
        mUserManager = new UserManager(this);
        mUserManager = mUserManager.LoadUserInfo();
        progressDialog = new LoadingDialog(this);
        initView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Object o) {
        if ("notification".equals(o.toString()))
            initBanner();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (netWork != null) {
            netWork.cancelTask();
            netWork = null;
        }

        if (sameNetDataJson != null) {
            sameNetDataJson.cancelTask();
            sameNetDataJson = null;
        }

        if (subnetWork != null) {
            subnetWork.cancelTask();
            subnetWork = null;
        }

        if (mNetModelDetail != null) {
            mNetModelDetail.cancelTask();
            mNetModelDetail = null;
        }
        EventBus.getDefault().unregister(this);
    }


    public void initBanner() {
        BannerBean bannerBean = GPJApplication.getInstance().mBannerBean;
        if (!isShowBanner && bannerBean != null && "success".equals(bannerBean.getStatus())) {
            isShowBanner = true;
            List<BannerBean.DataEntity.EvalEntity> dataEntities = bannerBean.getData().getSellcar();
            if (dataEntities != null && dataEntities.size() > 0) {
                Glide.with(this).load(dataEntities.get(0).getImg()).into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        int width = getResources().getDisplayMetrics().widthPixels;
                        int height = resource.getIntrinsicHeight() * width / resource.getIntrinsicWidth();
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
                        rollLinearLayout.addView(mRollPagerView, lp);
                    }
                });

                findViewById(R.id.image_top).setVisibility(View.GONE);
                mRollPagerView.setVisibility(View.VISIBLE);
                mLooperAdapter = new LooperAdapter(mRollPagerView, dataEntities, this, getSupportFragmentManager(), false);
                mRollPagerView.setAdapter(mLooperAdapter);
            }
        }
    }

    private void initView() {
        rollLinearLayout = (LinearLayout) findViewById(R.id.rollmain);
        mRollPagerView = new RollPagerView(this);
        mRollPagerView.setHintView(new ColorPointHintView(this, Color.WHITE, Color.GRAY));
        mRollPagerView.setPlayDelay(3000);
        mRollPagerView.setVisibility(View.GONE);
        mileTypeTextView = (TextView) findViewById(R.id.mile_type);
        initBanner();

        history = (TextView) findViewById(R.id.history);
        mImageView = (ImageView) findViewById(R.id.right_img);
        mImageView.setImageResource(R.drawable.kefu_phone);
        mTextView = (TextView) findViewById(R.id.right_title);
        mTextView.setText("客服");
        mTextView.setVisibility(View.VISIBLE);
        mImageView.setVisibility(View.VISIBLE);
        mImageView.setOnClickListener(this);
        mTextView.setOnClickListener(this);
        history.setOnClickListener(this);
        mLayoutInflater = LayoutInflater.from(this);
        mScrollView = (RLScrollView) findViewById(R.id.scrollview);
        sellcarButton = (Button) findViewById(R.id.sell_car_view);
        channelMainView = (LinearLayout) findViewById(R.id.channel_main);
        channelView1 = (LinearLayout) findViewById(R.id.channel_view1);
        channelView2 = (LinearLayout) findViewById(R.id.channel_view2);
        paimaiLinearLayout = (LinearLayout) findViewById(R.id.paimai_view);
        jishouLinearLayout = (LinearLayout) findViewById(R.id.jishou_view);

        mNextStepBtn = (Button) findViewById(R.id.btn_next_step);
        mDistanceEdit = (EditText) findViewById(R.id.editText);
        mGridView = (GridView) findViewById(R.id.gridview);
        mGridView.setAdapter(new MaterialAdapter(this));


        sellcarButton.setOnClickListener(this);
        mNextStepBtn.setOnClickListener(this);
        mNextStepBtn.setVisibility(View.GONE);

        carTypeText = (TextView) findViewById(R.id.txt_model);
        dateLicenseText = (TextView) findViewById(R.id.txt_year);
        cityText = (TextView) findViewById(R.id.txt_city);

        carTypeText.setOnClickListener(this);
        dateLicenseText.setOnClickListener(this);
        cityText.setOnClickListener(this);
        initListener();
        mAssessData = AssessmentData.getInstance();
        mBrandSlug = mAssessData.getBrandSlug();
        mModelSlug = mAssessData.getModelSlug();
        mModelDetailSlug = mAssessData.getModelDetailSlug();
        mBrandName = mAssessData.getBrandName();
        mModelName = mAssessData.getModelName();
        mModelDetailName = mAssessData.getModelDetailName();
        carTypeText.setText(mAssessData.getModelName() + " " + mAssessData.getModelDetailName());
        dateLicenseText.setText(mAssessData.getYear() + "年" + mAssessData.getMonth() + "月");
        mYear = mAssessData.getYear();
        mMonth = mAssessData.getMonth();
        double m = 0;
        if (!TextUtils.isEmpty(mAssessData.getMile())) {
            m = Double.parseDouble(mAssessData.getMile());
        }
        if (m % 1 == 0) {
            mDistanceEdit.setText((int) m + "");
        } else {
            mDistanceEdit.setText(mAssessData.getMile());
        }
        mileTypeTextView.setText("万公里");
        cityText.setText(mAssessData.getCity());
        mDistanceEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarSelectMile);
                    mileTypeTextView.setText("万公里");
                } else {
                    if (!TextUtils.isEmpty(mDistanceEdit.getText().toString())) {
                        mileTypeTextView.setText("万公里");
                    } else {
                        mileTypeTextView.setText("行驶里程");
                    }
                }
            }
        });
        //   carTypeText.setTextColor(Color.parseColor("#666666"));
        getMaxMinYear();
        step1();
    }

    @Override
    public void onClick(View v) {

        int id = v.getId();
        Intent it;
        switch (id) {
            // 选择车辆类型
            case R.id.txt_model:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarSelectBrand);
                if (!DataManager.getInstance().getLoadingDataSuccess()) {
                    Toast.makeText(this, "数据未加载成功,请检查网络是否连接!", Toast.LENGTH_SHORT).show();
                    return;
                }
                it = new Intent();
                it.setClass(this, CategoryActivity.class);
                it.putExtra(Const.BRAND_NAME_KEY, mBrandName);
                it.putExtra(Const.BRAND_SLUG_KEY, mBrandSlug);
                it.putExtra(Const.MODEL_NAME_KEY, mModelName);
                it.putExtra(Const.MODEL_SLUG_KEY, mModelSlug);
                it.putExtra(Const.MODEL_DETAIL_NAME_KEY, mModelDetailName);
                it.putExtra(Const.MODEL_DETAIL_SLUG_KEY, mModelDetailSlug);

                it.putExtra("needModelDetailFragment", true);
                startActivityForResult(it, REQUEST_CAR_TYPE);
                break;

            // 上牌时间
            case R.id.txt_year:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarSelectTime);
                if (TextUtils.isEmpty(carTypeText.getText().toString())
                        || carTypeText.getText().toString().equals("请选择您的爱车型号")) {
                    Toast.makeText(this, "请选择车辆型号!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (null != dateDialog && maxyear != null) {
                    dateDialog.show();
                } else {
                    Toast.makeText(this, "上牌时间数据加载中!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_next_step:
                step1();
                break;
            // 城市选择
            case R.id.txt_city:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarSelectCity);
                Intent intent = new Intent(this, CityActivity.class);
                intent.putExtra("needProvince", false);
                startActivityForResult(intent, REQUEST_CITY);
                break;
            case R.id.sell_car_view:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarCommit);
                StepMonitor.getInstance().addMonitor(new Monitor("click", "sell_submit", System.currentTimeMillis(), 1f));
                allPlats.clear();
                SelectShopSucceedData succeedData = SelectShopSucceedData.getInstance();
                succeedData.clearList();
                int size = sellCarPlatBean.getCooperation_dealers().size();
                for (int i = 0; i < size; i++) {
                    if (sellCarPlatBean.getCooperation_dealers().get(i).isChecked) {
                        allPlats.add(sellCarPlatBean.getCooperation_dealers().get(i));
                        succeedData.shopSucceed.add(succeedData.setShopAttribute(sellCarPlatBean.getCooperation_dealers().get(i).getCompany_name(), sellCarPlatBean.getCooperation_dealers().get(i).getLogo()));
                    }
                }
                if (allPlats.size() == 0) {
                    Toast.makeText(this, "请选择渠道", Toast.LENGTH_SHORT).show();
                    return;
                }
                sellCar();
                break;
            case R.id.right_img:
            case R.id.right_title:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarService);
                intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "4000253500"));
                startActivity(intent);
                break;
            case R.id.history:
                PointRecordManage.getInstance().addPoint(mySelf, SellCarReckonHistory);
                if (!GPJApplication.getInstance().isLogin()) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivityForResult(intent, HISTROY);
                    return;
                }
                intent = new Intent(this, FreeSellCarActivity.class);
                startActivityForResult(intent, EVAL_HISTORY);
                //startActivity(intent);
                break;
        }
    }

    private void step1() {
        if (TextUtils.isEmpty(carTypeText.getText().toString())
                || "请选择您的爱车型号".equals(carTypeText.getText().toString())) {
            Toast.makeText(this, "请选择车辆型号!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(dateLicenseText.getText().toString()) || "上牌时间".equals(dateLicenseText.getText().toString())) {
            Toast.makeText(this, "请选择上牌时间!", Toast.LENGTH_SHORT).show();
            return;
        }
        mile = mDistanceEdit.getText().toString();
        if (TextUtils.isEmpty(mile)) {
            Toast.makeText(this, "请输入里程!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mile.length() > 5) {
            Toast.makeText(this, "请输入正确的公里数，小数和整数均不能超过2位数!", Toast.LENGTH_SHORT).show();
            return;
        }
        Double distance = -1.0;
        try {
            distance = Double.valueOf(mile);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请填写正确的行驶里程（0-100万公里）", Toast.LENGTH_SHORT).show();
            return;
        }
        if (distance < 0 || distance > 100) {
            Toast.makeText(this, "请填写正确的行驶里程（0-100万公里）", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(cityText.getText().toString())) {
            Toast.makeText(this, "请选择城市!", Toast.LENGTH_SHORT).show();
            return;
        }
        mile = distance + "";
        getIfSameCar();
    }


    /**
     * 直接卖车
     */
    private void sellCar() {
        if (!progressDialog.isShowing())
            progressDialog.show();
        if (subnetWork == null) {
            subnetWork = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    progressDialog.dismiss();
                    String car_id = "";
                    String[] shopName = new String[0];
                    try {
                        car_id = json.getString("car_id");
                        JSONArray jsa = (JSONArray) json.get("success_dealers");
                        shopName = new String[jsa.length()];
                        for (int i = 0; i < jsa.length(); i++) {
                            shopName[i] = jsa.get(i).toString();
                        }
                    } catch (JSONException e) {
                    }
                    int size = shopName.length;
                    if (size > 0) {
                        Intent it = new Intent(WantSellCarActivity.this, SellSucceedActivity.class);
                        it.putExtra("shopName", shopName);
                        it.putExtra("car_id", car_id);
                        startActivity(it);
                    } else {
                        gotoNodears();
                    }
                }
            });
        }
        subnetWork.addParam("brand", mBrandSlug);
        subnetWork.addParam("model", mModelSlug);
        subnetWork.addParam("model_detail", mModelDetailSlug);
        subnetWork.addParam("year", mYear);
        subnetWork.addParam("month", mMonth);
        subnetWork.addParam("mile", mile);
        subnetWork.addParam("city", cityText.getText().toString());
        subnetWork.addParam("dealers", getDealers());
        subnetWork.addParam("contact", "AndroidUser");
        subnetWork.addParam("phone", getPhone());
        subnetWork.setUrl(API.pushCooperation);
        subnetWork.request("post");

    }

    private String getPhone() {
        if (TextUtils.isEmpty(mUserManager.getPhone())) {
            mUserManager = new UserManager(this);
            mUserManager = mUserManager.LoadUserInfo();
            return mUserManager.getPhone();
        }
        return mUserManager.getPhone();

    }

    //选中的商家 拼接成的字符串
    private String getDealers() {
        String Dealers = "";
        for (int i = 0; i < allPlats.size(); i++) {
            Dealers += allPlats.get(i).getCompany_name() + "-";
        }
        if (!TextUtils.isEmpty(Dealers)) {
            Dealers = Dealers.substring(0, Dealers.length() - 1);
            return Dealers;
        }
        return Dealers;
    }


    /**
     * 获取渠道个数
     */
    private void getDealerCount() {
        if (!progressDialog.isShowing())
            progressDialog.show();
        if (netWork == null) {
            netWork = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    progressDialog.dismiss();
                    Gson gson = new Gson();
                    sellCarPlatBean = gson.fromJson(json, SellCarPlatBean.class);
                    if ("success".equals(sellCarPlatBean.getStatus())) {
                        initChannelView();
                    } else {
                        Toast.makeText(getApplicationContext(), sellCarPlatBean.getMsg(), Toast.LENGTH_SHORT).show();
                    }

                }
            }, 1);
        }

        netWork.addParam("brand", mBrandSlug);
        netWork.addParam("model", mModelSlug);
        netWork.addParam("model_detail", mModelDetailSlug);
        netWork.addParam("city", cityText.getText().toString());
        netWork.addParam("mile", mile);
        netWork.addParam("month", mMonth);
        netWork.addParam("year", TextUtils.isEmpty(mYear) ? mAssessData.getYear() : mYear);
        netWork.setUrl(API.cooperationUrl);
        netWork.request("get");
    }

    private void initChannelView() {
        if (sellCarPlatBean == null || sellCarPlatBean.getCooperation_dealers().size() == 0) {
            channelMainView.setVisibility(View.GONE);
            gotoNodears();
            return;
        }
        channelMainView.setVisibility(View.VISIBLE);
        mNextStepBtn.setVisibility(View.GONE);

        paimais.clear();
        jishous.clear();
        int size = 0;
        List<SellCarPlatBean.CooperationDealersEntity> cooperationDealersEntities = sellCarPlatBean.getCooperation_dealers();
        size = cooperationDealersEntities.size();
        for (int i = 0; i < size; i++) {
            if ("dealer".equals(cooperationDealersEntities.get(i).getDealer_type())) {
                paimais.add(cooperationDealersEntities.get(i));
            } else {
                jishous.add(cooperationDealersEntities.get(i));
            }
        }

        size = paimais.size();
        if (size == 0) {
            channelView1.setVisibility(View.GONE);
        } else {
            channelView1.setVisibility(View.VISIBLE);
            paimaiLinearLayout.removeAllViews();
            for (int i = 0; i < size; i++) {
                View view = mLayoutInflater.inflate(R.layout.item_select_shop, null);
                ImageView networkImageView = (ImageView) view.findViewById(R.id.logo);
                TextView priceTextView = (TextView) view.findViewById(R.id.price);
                TextView numTextView = (TextView) view.findViewById(R.id.num);
                TextView crashTextView = (TextView) view.findViewById(R.id.crash);
                TextView car_tv = (TextView) view.findViewById(R.id.car_tv);
                final ImageView checkImageView = (ImageView) view.findViewById(R.id.check);
                ImageLoad.LoadImage(networkImageView, paimais.get(i).getLogo(), R.drawable.trans, R.drawable.trans,WantSellCarActivity.this);
                priceTextView.setText(paimais.get(i).getAverage_price() + "万元");
                String nums = paimais.get(i).getSell_count();
                numTextView.setText("已有 " + nums + " 人选择 | 返现");
                if (paimais.get(i).isChecked) {
                    checkImageView.setImageResource(R.drawable.sellcar_check);
                } else {
                    checkImageView.setImageResource(R.drawable.sellcar_uncheck);
                }
                car_tv.setText(paimais.get(i).getCompany_name());
                int crash = Integer.parseInt(paimais.get(i).getCashback());
                if (crash > 0) {
                    crashTextView.setText("返现" + crash + "元");
                } else {
                    crashTextView.setVisibility(View.GONE);
                }
                view.setTag(paimais.get(i));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SellCarPlatBean.CooperationDealersEntity entity = (SellCarPlatBean.CooperationDealersEntity) v.getTag();
                        entity.isChecked = !entity.isChecked;
                        if (entity.isChecked) {
                            checkImageView.setImageResource(R.drawable.sellcar_check);
                        } else {
                            checkImageView.setImageResource(R.drawable.sellcar_uncheck);
                        }
                    }
                });

                paimaiLinearLayout.addView(view);
            }
        }


        size = jishous.size();
        if (size == 0) {
            channelView2.setVisibility(View.GONE);
        } else {
            jishouLinearLayout.removeAllViews();
            channelView2.setVisibility(View.VISIBLE);
            for (int i = 0; i < size; i++) {
                View view = mLayoutInflater.inflate(R.layout.item_select_shop, null);
                ImageView networkImageView = (ImageView) view.findViewById(R.id.logo);
                TextView priceTextView = (TextView) view.findViewById(R.id.price);
                TextView numTextView = (TextView) view.findViewById(R.id.num);
                TextView crashTextView = (TextView) view.findViewById(R.id.crash);
                final ImageView checkImageView = (ImageView) view.findViewById(R.id.check);
                TextView car_tv = (TextView) view.findViewById(R.id.car_tv);
                ImageLoad.LoadImage(networkImageView, jishous.get(i).getLogo(), R.drawable.trans, R.drawable.trans,WantSellCarActivity.this);
                priceTextView.setText(jishous.get(i).getAverage_price() + "万元");
                String nums = jishous.get(i).getSell_count();
                numTextView.setText("已有 " + nums + " 人选择 | 返现");
                int crash = Integer.parseInt(jishous.get(i).getCashback());
                if (crash > 0) {
                    crashTextView.setText("返现" + crash + "元");
                } else {
                    crashTextView.setVisibility(View.GONE);
                }
                if (jishous.get(i).isChecked) {
                    checkImageView.setImageResource(R.drawable.sellcar_check);
                } else {
                    checkImageView.setImageResource(R.drawable.sellcar_uncheck);
                }
                car_tv.setText(jishous.get(i).getCompany_name());
                view.setTag(jishous.get(i));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarChoosePlatform);
                        SellCarPlatBean.CooperationDealersEntity entity = (SellCarPlatBean.CooperationDealersEntity) v.getTag();
                        entity.isChecked = !entity.isChecked;
                        if (entity.isChecked) {
                            checkImageView.setImageResource(R.drawable.sellcar_check);
                        } else {
                            checkImageView.setImageResource(R.drawable.sellcar_uncheck);
                        }
                    }
                });
                jishouLinearLayout.addView(view);
            }
        }

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                int[] location = new int[2];
                channelMainView.getLocationOnScreen(location);
                mScrollView.smoothScrollTo(0, location[1] - 100);
            }
        }, 200);


    }


    private void gotoNodears() {
        AssessmentData data = AssessmentData.getInstance();
        data.clear();
        data.setBrandName(mBrandName);
        data.setBrandSlug(mBrandSlug);
        data.setMile(mile);
        data.setModelDetailName(mModelDetailName);
        data.setModelDetailSlug(mModelDetailSlug);
        data.setModelName(mModelName);
        data.setModelSlug(mModelSlug);
        data.setModelThumbnail("");
        data.setMonth(mMonth + "");
        data.setYear(mYear + "");
        data.setCity(cityText.getText().toString());
        Intent intent = new Intent(this, NoDearsSellActivity.class);
        startActivity(intent);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CAR_TYPE:
                    onCarTypeSelect(data.getExtras(), 0);
                    break;
                case REQUEST_CITY:
                    String city = data.getExtras().getString("city");
                    if (city != null) {
                        cityText.setText(city);
                        clearPlats();
                    }
                    break;
                case Ass:
                    finish();
                    break;
                case HISTROY:
                    Intent intent = new Intent(this, FreeSellCarActivity.class);
                    startActivityForResult(intent, EVAL_HISTORY);
                    break;
                case EVAL_HISTORY:
                    AssessmentData mAssessData = AssessmentData.getInstance();
                    mBrandSlug = mAssessData.getBrandSlug();
                    mBrandName = mAssessData.getBrandName();
                    mModelSlug = mAssessData.getModelSlug();
                    mModelName = mAssessData.getModelName();
                    mModelDetailSlug = mAssessData.getModelDetailSlug();
                    mModelDetailName = mAssessData.getModelDetailName();
                    carTypeText.setText(mAssessData.getModelName() + " " + mAssessData.getModelDetailName());
                    dateLicenseText.setText(mAssessData.getYear() + "年" + mAssessData.getMonth() + "月");
                    mYear = mAssessData.getYear();
                    mMonth = mAssessData.getMonth();
                    getMaxMinYear();

                    double m = Double.parseDouble(mAssessData.getMile());
                    if (m % 1 == 0) {
                        mDistanceEdit.setText((int) m + "");
                    } else {
                        mDistanceEdit.setText(mAssessData.getMile());
                    }
                    cityText.setText(mAssessData.getCity());
                    //  carTypeText.setTextColor(Color.parseColor("#666666"));
                    clearPlats();
                    break;

            }
        }
    }


    private void getMaxMinYear() {
        if (mNetModelDetail == null) {
            mNetModelDetail = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    if (null == json) {
                        return;
                    }

                    try {
                        JSONArray detail = json.getJSONArray("detail_model");
                        if (null == detail) {
                            return;
                        }
                        for (int i = 0; i < detail.length(); i++) {
                            JSONObject jo = detail.getJSONObject(i);
                            if (null != jo) {
                                if (mModelDetailSlug.equals(jo.getString("detail_model_slug"))) {
                                    minyear = jo.getString("min_reg_year");
                                    maxyear = jo.getString("max_reg_year");
                                    break;
                                }
                            }
                        }
                    } catch (JSONException e) {

                    }

                    // 上牌年份选择弹框
                    dateDialog = new DatePickerDialog(WantSellCarActivity.this);
                    dateDialog.setMinMonth(1);
                    dateDialog.setMaxMonth(12);

                    dateDialog.setDialogCallBack(new DatePickerDialog.OnDialogCallBack() {

                        @Override
                        public void onSelectResult(String year, String month, String day) {
                            mYear = year;
                            mMonth = month;
                            if (TextUtils.isEmpty(month)) {
                                dateLicenseText.setText(year + "年");
                            } else {
                                dateLicenseText.setText(year + "年" + month + "月");
                            }
                        }


                    });
                    //   dateLicenseText.setTextColor(Color.parseColor("#666666"));
                    dateDialog.setMonthPickerVisibility(View.VISIBLE);
                    if (TextUtils.isEmpty(minyear) || TextUtils.isEmpty(maxyear)) {
                        dateDialog.setMinYear(2015);
                        dateDialog.setMaxYear(2017);
                    } else {
                        dateDialog.setMinYear(Integer.parseInt(minyear));
                        dateDialog.setMaxYear(Integer.parseInt(maxyear));
                    }
                }
            });
        }
        mNetModelDetail.setUrl(API.modelDetail);
        mNetModelDetail.addParam("brand", mBrandSlug);
        mNetModelDetail.addParam("model", mModelSlug);
        mNetModelDetail.request("get");
    }


    public void onCarTypeSelect(Bundle bundle, int type) {
        if (type == 0) {
            maxyear = null;
            minyear = null;
        }
        mBrandSlug = bundle.getString("brandSlug");
        mBrandName = bundle.getString("brandName");
        mModelSlug = bundle.getString("modelSlug");
        mModelName = bundle.getString("modelName");
        mModelDetailName = bundle.getString("modelDetailName");
        mModelDetailSlug = bundle.getString("modelDetailSlug");

        // 查询二手车,选择车型后,车辆型号TextView的展示
        if (mModelDetailName == null) {
            carTypeText.setText(mModelName);
        } else {
            carTypeText.setText(mModelName + " " + mModelDetailName);
        }

        //carTypeText.setTextColor(Color.parseColor("#666666"));

        // delete the date data if it is not null
        dateLicenseText.setText("请选择");
        // dateLicenseText.setTextColor(Color.parseColor("#18A0E0"));

        // 上牌年份选择弹框
        dateDialog = new DatePickerDialog(this);
        dateDialog.setMinMonth(1);
        dateDialog.setMaxMonth(12);

        dateDialog.setDialogCallBack(new OnDialogCallBack() {

            @Override
            public void onSelectResult(String year, String month, String day) {
                mYear = year;
                mMonth = month;
                if (TextUtils.isEmpty(month)) {
                    dateLicenseText.setText(year + "年");
                } else {
                    dateLicenseText.setText(year + "年" + month + "月");
                }
                //dateLicenseText.setTextColor(Color.parseColor("#666666"));
            }
        });

        maxyear = bundle.getString("maxyear");
        minyear = bundle.getString("minyear");

        dateDialog.setMonthPickerVisibility(View.VISIBLE);
        dateDialog.setMinYear(Integer.parseInt(minyear));
        dateDialog.setMaxYear(Integer.parseInt(maxyear));
        if (maxyear == null) {
            Toast.makeText(this, "没有可选的上牌时间!", Toast.LENGTH_SHORT).show();
            return;
        }
        mDistanceEdit.setText(null);


        if (TextUtils.isEmpty(carTypeText.getText().toString())
                || carTypeText.getText().toString().equals("请选择您的爱车型号")) {
            Toast.makeText(this, "请选择车辆型号!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (null != dateDialog && maxyear != null) {
            dateDialog.show();
        } else {
            Toast.makeText(this, "上牌时间数据加载中!", Toast.LENGTH_SHORT).show();
        }
        clearPlats();
    }


    private void clearPlats() {
        channelMainView.setVisibility(View.GONE);
        paimaiLinearLayout.removeAllViews();
        jishouLinearLayout.removeAllViews();
//        step1();
        mNextStepBtn.setVisibility(View.VISIBLE);
    }


    //是否重复购买
    private void getIfSameCar() {
        progressDialog.show();
        if (sameNetDataJson == null) {
            sameNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    progressDialog.dismiss();
                    getDealerCount();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    progressDialog.dismiss();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = json.getJSONObject("data");
                        if (jsonObject != null && jsonObject.length() > 0) {
                            PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarDuplicateAlert);
                            String title = jsonObject.getString("model_detail_zh");
                            String time = Utils.getParseDay("yyyy-MM-dd HH:mm:ss", jsonObject.getString("create_time"));
                            String msg = "您已在" + time + " ,提交一辆" + title + " 您已无需重复提交";
                            SellSameCarDialog sellSameCarDialog = new SellSameCarDialog(WantSellCarActivity.this, msg, new SellSameCarDialog.ISellSameCar() {
                                @Override
                                public void sellSmaeCar() {
                                    PointRecordManage.getInstance().addPoint(mySelf, Piont.SellCarDuplicateAlertConfirm);
                                    getDealerCount();
                                }

                                @Override
                                public void refresh() {
                                    Intent intent = new Intent(WantSellCarActivity.this, MainActivity.class);
                                    intent.putExtra("type", "sellCar");
                                    startActivity(intent);
                                }
                            }, false);
                            sellSameCarDialog.setCanceledOnTouchOutside(false);
                            sellSameCarDialog.show();
                        } else {
                            getDealerCount();
                        }
                    } catch (Exception e) {
                    }

                }
            });
        }
        sameNetDataJson.setUrl("/mobile/sell/car/get-check-duplicated-selling/");
        sameNetDataJson.addParam("brand", mBrandSlug);
        sameNetDataJson.addParam("model", mModelSlug);
        sameNetDataJson.addParam("model_detail", mModelDetailSlug);
        sameNetDataJson.addParam("type", "platform");
        sameNetDataJson.request("get");
    }


    private void initListener() {
        carTypeText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(carTypeText.getText().toString()) || "请选择您的爱车型号".equals(carTypeText.getText().toString())) {
                    carTypeText.setTextColor(Color.parseColor("#999999"));
                } else {
                    carTypeText.setTextColor(Color.parseColor("#333333"));
                }
            }
        });
        dateLicenseText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(dateLicenseText.getText().toString()) || "请选择".equals(dateLicenseText.getText().toString()) || "上牌时间".equals(dateLicenseText.getText().toString())) {
                    dateLicenseText.setTextColor(Color.parseColor("#999999"));
                } else {
                    dateLicenseText.setTextColor(Color.parseColor("#333333"));
                }
            }
        });


        mDistanceEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mDistanceEdit.getText().toString())) {
                    mDistanceEdit.setTextColor(Color.parseColor("#999999"));
                    mileTypeTextView.setTextColor(Color.parseColor("#999999"));
                } else {
                    mDistanceEdit.setTextColor(Color.parseColor("#333333"));
                    mileTypeTextView.setTextColor(Color.parseColor("#333333"));
                }
            }
        });
        cityText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(cityText.getText().toString()) || "上牌城市".equals(cityText.getText().toString())) {
                    cityText.setTextColor(Color.parseColor("#999999"));
                } else {
                    cityText.setTextColor(Color.parseColor("#333333"));
                }
            }
        });
    }

}
